package org.zgjy;

import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import org.zgjy.model.Device;
import org.zgjy.model.Field;
import org.zgjy.model.MqttMsg;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


public class ModbusTimerTask extends TimerTask{

    public String name;
    //public List<Device> devices;
    public List<DevicePeer> devicePeers = new ArrayList<>();

    public static ArrayList<DeviceConfig> configs;
    public final ArrayList<MqttMsg> msgQueue = new ArrayList<>();

    public ModbusTimerTask(String name, List<Device> devices) {
        this.name = name;
        //this.devices = devices;
        for(Device device: devices){
            devicePeers.add(new DevicePeer(device));
        }
    }

    public static DeviceConfig search_config(String pId){

        for(DeviceConfig dc:ModbusTimerTask.configs){
            if(dc.machineType.productId.equals(pId)){
                return dc;
            }
        }
        return null;
    }

    @Override
    public void run() {

        //System.out.println("ModbusTimerTask:" + this.name);
        //System.out.println("ModbusTimerTask:" + this.devices.toString());
        String strTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        System.out.println("ModbusTimerTask:" + Thread.currentThread().getId() + " Time:" + strTime);

        for(DevicePeer devicePeer : this.devicePeers){

            Device device = devicePeer.device;
            DeviceConfig config = ModbusTimerTask.search_config(device.productId);
            if(config == null){
                System.out.println("找不到productId的配置文件: " + device.productId);
                continue;
            }

            devicePeer.initial_modbus();
            if(!devicePeer.test_connectivity()){
                continue;
            }
            try {
                String tail = ",\"macId\":" + device.id + ",\"macNo\":\"" + device.getMacNo() + "\"}";
                String result = "{";
                String data ;
                for(Field field : config.fields){

                    //ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, 0x0, 10);
                    ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, field.addr, 1);
                    ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) devicePeer.send(request);

                    if (response.isException())
                        System.out.println("Exception response: message=" + response.getExceptionMessage());
                    else{
                        short[] shortData = response.getShortData();
                        data = String.valueOf(shortData[0]);
                        // "FR_meter":231
                        if(result.length()==1)
                            result = result + "\"" + field.mqtt_tag + "\":" + data;
                        else
                            result = result + ",\"" + field.mqtt_tag + "\":" + data;
                    }
                }

                result = result + tail;
                System.out.println(result);
                long ts = new Date().getTime();

                // 加入 mqtt消息发送队列
                this.msgQueue.add(new MqttMsg(String.valueOf(device.id), device.macNo, ts, result, ""));

            }
            catch (ModbusTransportException e) {
                e.printStackTrace();
            }

            System.out.println("Modbus4j Test !!!");
        }
    }
}
